# coding=utf-8
import arcpy
import math
import json

path = r'D:\WorkData\20250712四川河流\0811'
arcpy.env.workspace = path
arcpy.env.overwriteOutput = True
spatial_ref = arcpy.SpatialReference(4326)
riv = r'D:\WorkData\20250712四川河流\0811\四川.shp'.decode('utf-8')
lp = r'D:\WorkData\20250712四川河流\0811\0808.shp'.decode('utf-8')

cs1 = arcpy.da.SearchCursor(lp,['SHAPE@','name','dis','n_riv_name','n_riv_id','n_riv_lv','FID'])

j = 0;
for row1 in cs1:
    try:
        pointListWKT = []
        print j,row1[1],row1[3],row1[4]
        n_riv_id = int(row1[4])
        expression = "rivId = '{}'".format(n_riv_id)

        pointList = []
        dis = 1
        insIndex = 0

        cs2 = arcpy.da.SearchCursor(riv, ['SHAPE@', 'SHAPE@X', 'SHAPE@Y','rivid'], where_clause=expression,explode_to_points=True)
        i = 0
        for row2 in cs2:
            pointList.append([row2[1], row2[2]])
            if (row1[0].distanceTo(row2[0]) < dis):
                insIndex = i
                dis = row1[0].distanceTo(row2[0])
            i += 1
        x1 = pointList[insIndex][0]
        y1 = pointList[insIndex][1]
        x2 = pointList[insIndex - 1][0]
        y2 = pointList[insIndex - 1][1]

        segmentLength = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
        pointX = row1[0].centroid.X
        pointY = row1[0].centroid.Y
        pToSegmentSP = math.sqrt((pointX - x2) ** 2 + (pointY - y2) ** 2)
        if (segmentLength > pToSegmentSP):
            pointList.insert(insIndex, [pointX, pointY])
        else:
            pointList.insert(insIndex + 1, [pointX, pointY])

        pointListWKT = [pointList]

        with arcpy.da.UpdateCursor(riv, 'SHAPE@JSON') as yb:
            for row in yb:
                geoJson = json.loads(row[0])
                geoJson['paths'] = pointListWKT
                row[0] = json.dumps(geoJson)
                yb.updateRow(row)

        j += 1
    except:
         print '!!!!!!!!!!',j,row1[1],row1[3],row1[4]